import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Note {
  id: string
  folderId: string
  title: string
  content: string
  isPinned: boolean
  isLocked: boolean
  createdAt: Date
  updatedAt: Date
}

export interface Folder {
  id: string
  name: string
  icon: string
  color: string
  count?: number
  isSystem?: boolean
}

export const useNotesStore = defineStore('notes', () => {
  // 文件夹
  const folders = ref<Folder[]>([
    { id: 'all', name: '所有 iCloud', icon: '☁️', color: '#007AFF', isSystem: true },
    { id: 'notes', name: '备忘录', icon: '📝', color: '#FFD60A', isSystem: true },
    { id: 'work', name: '工作', icon: '💼', color: '#FF9F0A', isSystem: false },
    { id: 'personal', name: '个人', icon: '👤', color: '#5856D6', isSystem: false },
  ])

  // 备忘录
  const notes = ref<Note[]>([
    {
      id: '1',
      folderId: 'notes',
      title: '欢迎使用备忘录',
      content: '# 欢迎使用备忘录\n\n这是一个功能强大的备忘录应用。\n\n## 主要功能\n\n• 支持富文本编辑\n• 支持Markdown语法\n• 支持文件夹分组\n• 支持固定重要备忘录\n\n开始记录您的想法吧！',
      isPinned: true,
      isLocked: false,
      createdAt: new Date('2025-10-20'),
      updatedAt: new Date('2025-10-23'),
    },
    {
      id: '2',
      folderId: 'work',
      title: '项目会议记录',
      content: '# 项目会议记录\n\n**日期**: 2025-10-23\n**参与人**: 张三、李四、王五\n\n## 讨论内容\n\n1. 项目进度回顾\n2. 下周工作安排\n3. 技术难点讨论',
      isPinned: false,
      isLocked: false,
      createdAt: new Date('2025-10-23'),
      updatedAt: new Date('2025-10-23'),
    },
    {
      id: '3',
      folderId: 'personal',
      title: '购物清单',
      content: '# 购物清单\n\n- [ ] 牛奶\n- [ ] 面包\n- [ ] 鸡蛋\n- [ ] 水果\n- [x] 蔬菜',
      isPinned: false,
      isLocked: false,
      createdAt: new Date('2025-10-22'),
      updatedAt: new Date('2025-10-23'),
    },
  ])

  // 当前选中的文件夹和备忘录
  const selectedFolderId = ref('all')
  const selectedNoteId = ref<string | null>('1')
  const searchQuery = ref('')

  // 计算属性：当前文件夹的备忘录列表
  const currentFolderNotes = computed(() => {
    let filteredNotes = notes.value

    // 按文件夹筛选
    if (selectedFolderId.value !== 'all') {
      filteredNotes = filteredNotes.filter(note => note.folderId === selectedFolderId.value)
    }

    // 搜索筛选
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filteredNotes = filteredNotes.filter(note =>
        note.title.toLowerCase().includes(query) ||
        note.content.toLowerCase().includes(query)
      )
    }

    // 排序：固定的在前，然后按更新时间
    return filteredNotes.sort((a, b) => {
      if (a.isPinned && !b.isPinned) return -1
      if (!a.isPinned && b.isPinned) return 1
      return b.updatedAt.getTime() - a.updatedAt.getTime()
    })
  })

  // 计算属性：当前选中的备忘录
  const selectedNote = computed(() => {
    return notes.value.find(note => note.id === selectedNoteId.value) || null
  })

  // 计算属性：更新文件夹的备忘录数量
  const foldersWithCount = computed(() => {
    return folders.value.map(folder => {
      const count = folder.id === 'all'
        ? notes.value.length
        : notes.value.filter(note => note.folderId === folder.id).length
      return { ...folder, count }
    })
  })

  // 选择文件夹
  function selectFolder(folderId: string) {
    selectedFolderId.value = folderId
    // 选择该文件夹的第一个备忘录
    const firstNote = currentFolderNotes.value[0]
    selectedNoteId.value = firstNote ? firstNote.id : null
  }

  // 选择备忘录
  function selectNote(noteId: string) {
    selectedNoteId.value = noteId
  }

  // 创建新备忘录
  function createNote(folderId?: string) {
    const targetFolderId = folderId || selectedFolderId.value
    const finalFolderId = targetFolderId === 'all' ? 'notes' : targetFolderId

    const newNote: Note = {
      id: Date.now().toString(),
      folderId: finalFolderId,
      title: '新建备忘录',
      content: '',
      isPinned: false,
      isLocked: false,
      createdAt: new Date(),
      updatedAt: new Date(),
    }

    notes.value.unshift(newNote)
    selectedNoteId.value = newNote.id
    return newNote
  }

  // 更新备忘录
  function updateNote(noteId: string, updates: Partial<Note>) {
    const note = notes.value.find(n => n.id === noteId)
    if (note) {
      Object.assign(note, updates, { updatedAt: new Date() })
      saveToLocalStorage()
    }
  }

  // 删除备忘录
  function deleteNote(noteId: string) {
    const index = notes.value.findIndex(n => n.id === noteId)
    if (index !== -1) {
      notes.value.splice(index, 1)
      // 如果删除的是当前选中的，选择下一个
      if (selectedNoteId.value === noteId) {
        const nextNote = currentFolderNotes.value[0]
        selectedNoteId.value = nextNote ? nextNote.id : null
      }
      saveToLocalStorage()
    }
  }

  // 切换固定状态
  function togglePin(noteId: string) {
    const note = notes.value.find(n => n.id === noteId)
    if (note) {
      note.isPinned = !note.isPinned
      note.updatedAt = new Date()
      saveToLocalStorage()
    }
  }

  // 切换锁定状态
  function toggleLock(noteId: string) {
    const note = notes.value.find(n => n.id === noteId)
    if (note) {
      note.isLocked = !note.isLocked
      saveToLocalStorage()
    }
  }

  // 创建文件夹
  function createFolder(name: string, icon: string = '📁', color: string = '#8E8E93') {
    const newFolder: Folder = {
      id: Date.now().toString(),
      name,
      icon,
      color,
      isSystem: false,
    }
    folders.value.push(newFolder)
    saveToLocalStorage()
    return newFolder
  }

  // 删除文件夹（将备忘录移到默认文件夹）
  function deleteFolder(folderId: string) {
    const folder = folders.value.find(f => f.id === folderId)
    if (!folder || folder.isSystem) return

    // 将该文件夹的备忘录移到默认文件夹
    notes.value.forEach(note => {
      if (note.folderId === folderId) {
        note.folderId = 'notes'
      }
    })

    // 删除文件夹
    const index = folders.value.findIndex(f => f.id === folderId)
    if (index !== -1) {
      folders.value.splice(index, 1)
    }

    // 如果删除的是当前选中的文件夹，切换到全部
    if (selectedFolderId.value === folderId) {
      selectFolder('all')
    }

    saveToLocalStorage()
  }

  // 保存到 localStorage
  function saveToLocalStorage() {
    localStorage.setItem('macos-notes', JSON.stringify({
      notes: notes.value,
      folders: folders.value.filter(f => !f.isSystem),
    }))
  }

  // 从 localStorage 加载
  function loadFromLocalStorage() {
    const saved = localStorage.getItem('macos-notes')
    if (saved) {
      try {
        const data = JSON.parse(saved)
        if (data.notes) {
          // 恢复日期对象
          notes.value = data.notes.map((note: any) => ({
            ...note,
            createdAt: new Date(note.createdAt),
            updatedAt: new Date(note.updatedAt),
          }))
        }
        if (data.folders) {
          // 合并自定义文件夹和系统文件夹
          const systemFolders = folders.value.filter(f => f.isSystem)
          folders.value = [...systemFolders, ...data.folders]
        }
      } catch (e) {
        console.error('Failed to load notes from localStorage:', e)
      }
    }
  }

  // 清除所有数据
  function clearNotesCache() {
    notes.value = []
    folders.value = folders.value.filter(f => f.isSystem)
    selectedFolderId.value = 'all'
    selectedNoteId.value = null
    searchQuery.value = ''
    localStorage.removeItem('macos-notes')
  }

  // 初始化时加载数据
  loadFromLocalStorage()

  return {
    folders,
    notes,
    selectedFolderId,
    selectedNoteId,
    searchQuery,
    currentFolderNotes,
    selectedNote,
    foldersWithCount,
    selectFolder,
    selectNote,
    createNote,
    updateNote,
    deleteNote,
    togglePin,
    toggleLock,
    createFolder,
    deleteFolder,
    clearNotesCache,
  }
})

